<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\api\model\project\ProjectApply;
use app\api\model\project\ProjectOrderComplain;
use app\api\model\project\ProjectStaff;
use app\common\controller\Api;
use app\api\model\project\ProjectOrderUnion as ProjectOrderUnionModel;
use app\api\model\project\ProjectOrder as ProjectOrderModel;
use think\Db;

//用户的订单操作
class Projectorder extends Api
{

    protected $noNeedRight = ['*'];

    //是否已申请服务
    public function issign()
    {
        $staff_id = input('staff_id',0);

        $orderinfo = ProjectOrderModel::get(['user_id'=>$this->auth->id, 'staff_id'=>$staff_id]);

        $this->success('',$orderinfo?$orderinfo['order_id']:0);
    }


    //创建订单
    public function create()
    {
        try {
            $model = new ProjectOrderUnionModel();
            $param = input();
            $param['user_id'] = $this->auth->id;
            $res = $model->add($param);

        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('提交成功',$res);

    }



    //回调-合单
    public function unionnotify()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();

        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }

            \think\Log::record($data);
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];

            \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");

            //你可以在此编写订单逻辑

            $model = new ProjectOrderUnionModel();

            $res = $model->notify($out_trade_no,$paytype);
        } catch (\Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }

    //回调
    public function notify()
    {
        $paytype = $this->request->param('paytype');
        $pay = Service::checkNotify($paytype);
        if (!$pay) {
            return json(['code' => 'FAIL', 'message' => '失败'], 500, ['Content-Type' => 'application/json']);
        }

        // 获取回调数据，V3和V2的回调接收不同
        $data = Service::isVersionV3() ? $pay->callback() : $pay->verify();

        try {
            //微信支付V3返回和V2不同
            if (Service::isVersionV3() && $paytype === 'wechat') {
                $data = $data['resource']['ciphertext'];
                $data['total_fee'] = $data['amount']['total'];
            }

            \think\Log::record($data);
            //获取支付金额、订单号
            $payamount = $paytype == 'alipay' ? $data['total_amount'] : $data['total_fee'] / 100;
            $out_trade_no = $data['out_trade_no'];

            \think\Log::record("回调成功，订单号：{$out_trade_no}，金额：{$payamount}");

            //你可以在此编写订单逻辑

            $model = new ProjectOrderModel();

            $res = $model->notify($out_trade_no,$paytype);
        } catch (\Exception $e) {
            \think\Log::record("回调逻辑处理错误:" . $e->getMessage(), "error");
        }

        //下面这句必须要执行,且在此之前不能有任何输出
        if (Service::isVersionV3()) {
            return $pay->success()->getBody()->getContents();
        } else {
            return $pay->success()->send();
        }
    }

    //支付
    public function pay()
    {
        $order_no = input('order_no','');
        $type = input('type',0);//0是合单支付,1是单个订单支付
        $pay_type = input('pay_type','wechat');
        $method = input('method','app');
        $request = request();
        if ($type==0){
            $order = ProjectOrderUnionModel::get(['order_no'=>$order_no]);
            $project_apply = ProjectApply::where('id','in',$order->apply_id)->column('name');
            $title = implode(',',$project_apply);
            $notifyurl =  $request->root(true)."/api/projectorder/unionnotify";
        } else {
            $order = ProjectOrderModel::get(['order_no'=>$order_no]);

            $notifyurl =  $request->root(true)."/api/projectorder/notify";
            $title = $order['project_name'];
        }

        if (!$order){
            $this->error('订单不存在');
        }
        try {
            $pay = \addons\epay\library\Service::submitOrder($order['pay_price'],$order['order_no'],$pay_type,$title,$notifyurl,'',$method);
        }catch (\Exception $e) {
            // 回滚事务

           $this->error($e->getMessage());
        }

        $this->success('',$pay);
    }

    //线下支付
    public function offlinepay()
    {
        $order_no = input('order_no','');
        $pay_type = input('pay_type','wechat');

        //$model = new ProjectOrderModel();
        $model = new ProjectOrderUnionModel();
        $res = $model->notify($order_no,$pay_type);
        $this->success('提交成功',$res);
    }

    //我的订单
    public function orderlist()
    {
        $order_status = input('order_status','all');

        $where = ['po.user_id'=>$this->auth->id];

        switch ( $order_status ) {
            case "waitpay"://待付款
                $where['po.order_status'] = 0;
                break;
            case "waitservice"://待服务
                $where['po.order_status'] = 1;
                break;
            case "serviceing"://服务中
                $where['po.order_status'] = 2;
                break;
            case "end"://服务结束
                $where['po.order_status'] = 3;
                break;
            case "complete"://已完成
                $where['po.order_status'] = 4;
                break;
            case "other"://其他
                $where['po.order_status'] = ['in',[-1,0,5]];
                break;
        }

        $list = ProjectOrderModel::alias('po')
            ->join('project_staff ps','po.staff_id = ps.id')
            ->where($where)
            ->field('po.*,ps.realname')
            ->order('po.createtime desc')
            ->paginate(10, false, ['query' => request()->get()]);

        $auto_close = \app\common\model\Config::get(['name'=>'close_time'])->value*60;

        foreach ($list as $k=>$v){
            $list[$k]['auto_close'] = $v['createtime'] + $auto_close-time();
        }

        $this->success('提交成功',$list);
    }

    //取消订单
    public function cancel()
    {
        try {
            $model = new ProjectOrderModel();
            $order_id = input('order_id',0);

            $res = $model->cancel($order_id,$this->auth->id);

        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('提交成功',$res);

    }

    //订单详情
    public function info()
    {
        $order_id = input('order_id',0);

        $info = ProjectOrderModel::get($order_id);

        if (!$info)$this->error('订单不存在');
        $auto_close = \app\common\model\Config::get(['name'=>'close_time'])->value*60;
        $info['auto_close'] = $info['createtime'] + $auto_close-time();
        $info['staff_info'] = ProjectStaff::get($info->staff_id);
        $info['order_execute'] = \app\common\model\Config::get(['name'=>'order_execute'])->value;
        $info['service_start'] = \app\common\model\Config::get(['name'=>'service_start'])->value;
        $info['order_dispute'] = \app\common\model\Config::get(['name'=>'order_dispute'])->value;
        $this->success('',$info);
    }

    //退单
    public function refund()
    {
        try {
            $model = new ProjectOrderModel();
            $order_id = input('order_id',0);

            $res = $model->refund($order_id,$this->auth->id);

        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('提交成功',$res);

    }

    //投诉
    public function complain()
    {
        $order_id = input('order_id',0);
        $reason = input('reason','');
        $explain = input('explain','');
        $images = input('images','');
        $video = input('video','');
        $info = ProjectOrderModel::get($order_id);

        if (!$info)$this->error('订单不存在');
        $complain_info = ProjectOrderComplain::where([ 'user_id'=>$this->auth->id,'order_id'=>$order_id])->find();
        if ($complain_info)$this->error('已投诉');
        $complain_model = new ProjectOrderComplain();

        $data = [
            'user_id'=>$this->auth->id,
            'order_id'=>$order_id,
            'reason'=>$reason,
            'explain'=>$explain,
            'images'=>$images,
            'video'=>$video
        ];

        $res = $complain_model->save($data);
        if ($res){
            $this->success('投诉成功');
        } else {
            $this->error('投诉失败');
        }
    }



}